package com.shop.cereshop.business.service.feedback.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cereshop.business.dao.feedback.FeedbackDAO;
import com.shop.cereshop.business.service.feedback.FeedbackImageService;
import com.shop.cereshop.business.service.feedback.FeedbackService;
import com.shop.cereshop.commons.constant.FeedbackConstant;
import com.shop.cereshop.commons.domain.feedback.Feedback;
import com.shop.cereshop.commons.domain.feedback.FeedbackImage;
import com.shop.cereshop.commons.param.feedback.SubmitFeedbackDTO;
import com.shop.cereshop.commons.utils.EmptyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户反馈服务实现类
 * 
 * @author lx
 */
@Service
@RequiredArgsConstructor
public class FeedbackServiceImpl extends ServiceImpl<FeedbackDAO, Feedback> implements FeedbackService {

  private final FeedbackDAO feedbackDAO;

  private final FeedbackImageService feedbackImageService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int submitFeedback(SubmitFeedbackDTO submitFeedbackDTO) {
    // 1. 先保存反馈记录
    Feedback feedback = new Feedback();
    feedback.setUserId(submitFeedbackDTO.getUserId());
    feedback.setUserType(submitFeedbackDTO.getUserType());
    feedback.setContent(submitFeedbackDTO.getContent());
    feedback.setState(FeedbackConstant.FeedbackState.PENDING);
    LocalDateTime now = LocalDateTime.now();
    feedback.setCreateTime(now);
    feedback.setUpdateTime(now);

    // 使用save方法确保主键能正确回填到实体对象中
    int saved = feedbackDAO.insert(feedback);

    // 2. 如果保存成功且有图片，则保存图片记录并关联反馈ID
    if (saved > 0 && !EmptyUtils.isEmpty(submitFeedbackDTO.getImageList())) {
      List<FeedbackImage> feedbackImages = new ArrayList<>();
      for (String image : submitFeedbackDTO.getImageList()) {
        FeedbackImage feedbackImage = new FeedbackImage();
        feedbackImage.setImageUrl(image);
        feedbackImage.setFeedbackId(feedback.getFeedbackId());
        feedbackImages.add(feedbackImage);
      }
      feedbackImageService.saveBatch(feedbackImages);
    }

    return saved;
  }
}